package com.wedistudio.scribd;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.simpleframework.xml.Serializer;

import com.wedistudio.android.framework.fetcher.URLBuilder;
import com.wedistudio.android.framework.fetcher.URLParams;
import com.wedistudio.android.framework.pool.PoolFactory;
import com.wedistudio.android.framework.service.ServiceException;
import com.wedistudio.scribd.xml.RSP;

public class ScribdUtils {

	public static String SOURCE = "scribd";
	public static final String API_URL_BASE = "http://api.scribd.com/api";
	private static final String API_KEY = "2gpeex8421ihovahlxoqd";
	//private static final String API_PASS = "sec-26zwx2u8j8hrh3ytqm6fpwa7b0";

	public static final String md5(final String s) {
	    try {
	        // Create MD5 Hash
	        MessageDigest digest = java.security.MessageDigest
	                .getInstance("MD5");
	        digest.update(s.getBytes());
	        byte messageDigest[] = digest.digest();

	        // Create Hex String
	        StringBuffer hexString = new StringBuffer();
	        for (int i = 0; i < messageDigest.length; i++) {
	            String h = Integer.toHexString(0xFF & messageDigest[i]);
	            while (h.length() < 2)
	                h = "0" + h;
	            hexString.append(h);
	        }
	        return hexString.toString();

	    } catch (NoSuchAlgorithmException e) {
	        e.printStackTrace();
	    }
	    return "";
	}
	
	private static void addCredentials(URLParams params) {
		params.addParam("api_key", API_KEY);
	}

	public static URLParams buildURLParams(String action) {
		URLParams params = URLParams.create(URLBuilder.create(API_URL_BASE));
		params.addParam("method", action);
		addCredentials(params);
		return params;
	}

	public static RSP getResponse(String xml) {
		Serializer serializer = null;
		String message = null;
		try {
			serializer = PoolFactory.get(Serializer.class);
			RSP rsp = serializer.read(RSP.class, xml);
			if (rsp.error != null)
				message = rsp.error.message;

			return rsp;
		} catch (Throwable e) {
			throw new ServiceException(e);
		} finally {
			PoolFactory.release(serializer, Serializer.class);
			if (message != null)
				throw new ServiceException(message);
		}
	}
}
